const { createApp } = Vue;

createApp({
    data() {
        return {
            details: [],
            templates: [],
            selectedTemplate: '',
            currentPage: 1,
            pageSize: 50,
            total: 0,
            loading: false,
            currentDetail: {},
            selectedItems: [],
            zoomLevel: 100,
            hasMore: true,
            stats: {
                total: 0,
                pending: 0,
                approved: 0,
                rejected: 0
            }
        }
    },
    computed: {
        selectAll: {
            get() {
                return this.details.length > 0 && this.selectedItems.length === this.details.length;
            },
            set(value) {
                this.selectedItems = value ? this.details.map(item => item.id) : [];
            }
        }
    },
    methods: {
        async loadTemplates() {
            try {
                const response = await fetch('/api/admin/templates');
                const data = await response.json();
                if (data.code === 200) {
                    this.templates = data.data;
                }
            } catch (error) {
                console.error('加载模板列表失败:', error);
            }
        },
        async loadDetails() {
            this.loading = true;
            try {
                // 保存当前滚动位置
                const container = document.querySelector('.table-responsive');
                const scrollTop = container ? container.scrollTop : 0;

                const response = await fetch(`/api/admin/details?page=${this.currentPage}&size=${this.pageSize}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    if (this.currentPage === 1) {
                        this.details = data.data;
                    } else {
                        this.details = [...this.details, ...data.data];
                    }
                    this.total = data.total;
                    this.hasMore = this.details.length < this.total;

                    // 在 DOM 更新后恢复滚动位置
                    this.$nextTick(() => {
                        if (container && this.currentPage > 1) {
                            container.scrollTop = scrollTop;
                        }
                    });
                } else {
                    throw new Error(data.msg || '加载失败');
                }
            } catch (error) {
                console.error('加载审核列表失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '加载失败',
                    text: error.message || '请重试'
                });
            } finally {
                this.loading = false;
            }
        },
        async showImages(detail) {
            // 显示加载提示
            const loadingToast = Swal.fire({
                title: '加载图片中...',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            try {
                const response = await fetch(`/api/admin/details/release?task_id=${detail.task_id}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    this.currentDetail = {
                        ...detail,
                        release_data: data.data.data
                    };
                    // 预加载图片
                    const imagePaths = JSON.parse(detail.image_paths || '[]');
                    await Promise.all(imagePaths.map(image => {
                        return new Promise((resolve, reject) => {
                            const img = new Image();
                            img.onload = resolve;
                            img.onerror = reject;
                            img.src = image.url;
                        });
                    }));
                } else {
                    throw new Error(data.msg || '获取数据失败');
                }
            } catch (error) {
                console.error('获取图片详情失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '获取失败',
                    text: error.message || '请重试'
                });
            } finally {
                // 关闭加载提示
                loadingToast.close();
            }
        },
        async handleAudit(detail, status) {
            try {
                const response = await fetch('/api/admin/audit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        id: detail.id,
                        status: status
                    })
                });

                const data = await response.json();
                if (data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '审核成功',
                        showConfirmButton: false,
                        timer: 1500
                    });
                    this.loadDetails();
                    if (this.currentDetail.id === detail.id) {
                        this.currentDetail = {};
                    }
                } else {
                    throw new Error(data.msg || '审核失败');
                }
            } catch (error) {
                console.error('审核失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '审核失败',
                    text: error.message || '请重试'
                });
            }
        },
        getStatusText(status) {
            const statusMap = {
                '0': '未审核',
                '1': '已通过',
                '2': '已拒绝'
            };
            return statusMap[status] || '未知状态';
        },
        getStatusClass(status) {
            const classMap = {
                '0': 'bg-warning',
                '1': 'bg-success',
                '2': 'bg-danger'
            };
            return classMap[status] || 'bg-secondary';
        },
        handleSelectAll(e) {
            if (e.target.checked) {
                this.selectedItems = this.details.map(item => item.id);
            } else {
                this.selectedItems = [];
            }
        },
        async handleBatchApprove() {
            const result = await Swal.fire({
                title: '批量通过',
                text: `确定要通过选中的 ${this.selectedItems.length} 条记录吗？`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '确定通过',
                cancelButtonText: '取消',
                confirmButtonColor: '#28a745'
            });

            if (result.isConfirmed) {
                // 创建一个固定的进度提示
                const progressSwal = Swal.fire({
                    title: '处理中...',
                    html: '准备开始处理...',
                    allowOutsideClick: false,
                    allowEscapeKey: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                try {
                    let success = 0;
                    let failed = 0;
                    
                    for (let i = 0; i < this.selectedItems.length; i++) {
                        const id = this.selectedItems[i];
                        try {
                            const response = await fetch('/api/admin/audit', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    id: id,
                                    status: 1
                                })
                            });

                            const data = await response.json();
                            if (data.code === 200) {
                                success++;
                            } else {
                                failed++;
                            }

                            // 更新进度
                            const progress = Math.round(((i + 1) / this.selectedItems.length) * 100);
                            Swal.update({
                                html: `
                                    <div class="mb-2">正在处理 ${i + 1}/${this.selectedItems.length}</div>
                                    <div class="progress">
                                        <div class="progress-bar" role="progressbar" 
                                             style="width: ${progress}%" 
                                             aria-valuenow="${progress}" 
                                             aria-valuemin="0" 
                                             aria-valuemax="100">
                                            ${progress}%
                                        </div>
                                    </div>
                                `
                            });
                        } catch (error) {
                            failed++;
                            console.error(`审核ID ${id} 失败:`, error);
                        }
                    }

                    // 关闭进度提示
                    progressSwal.close();

                    // 显示最终结果
                    await Swal.fire({
                        icon: success > 0 ? 'success' : 'warning',
                        title: '批量审核完成',
                        html: `
                            成功: ${success} 条<br>
                            失败: ${failed} 条
                        `,
                        confirmButtonText: '确定'
                    });

                    this.selectedItems = [];
                    this.loadDetails();
                } catch (error) {
                    console.error('批量审核失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '审核失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },
        async handleBatchReject() {
            const result = await Swal.fire({
                title: '批量拒绝',
                text: `确定要拒绝选中的 ${this.selectedItems.length} 条记录吗？`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定拒绝',
                cancelButtonText: '取消',
                confirmButtonColor: '#dc3545'
            });

            if (result.isConfirmed) {
                // 创建进度提示
                const progressSwal = Swal.mixin({
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true
                });

                try {
                    let success = 0;
                    let failed = 0;
                    
                    for (let i = 0; i < this.selectedItems.length; i++) {
                        const id = this.selectedItems[i];
                        try {
                            const response = await fetch('/api/admin/audit', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    id: id,
                                    status: 2
                                })
                            });

                            const data = await response.json();
                            if (data.code === 200) {
                                success++;
                            } else {
                                failed++;
                            }

                            // 更新进度
                            const progress = Math.round(((i + 1) / this.selectedItems.length) * 100);
                            await progressSwal.fire({
                                title: `正在处理 ${i + 1}/${this.selectedItems.length}`,
                                html: `
                                    <div class="progress">
                                        <div class="progress-bar bg-danger" role="progressbar" 
                                             style="width: ${progress}%" 
                                             aria-valuenow="${progress}" 
                                             aria-valuemin="0" 
                                             aria-valuemax="100">
                                            ${progress}%
                                        </div>
                                    </div>
                                `
                            });
                        } catch (error) {
                            failed++;
                            console.error(`审核ID ${id} 失败:`, error);
                        }
                    }

                    // 显示最终结果
                    await Swal.fire({
                        icon: success > 0 ? 'success' : 'warning',
                        title: '批量审核完成',
                        html: `
                            成功: ${success} 条<br>
                            失败: ${failed} 条
                        `,
                        confirmButtonText: '确定'
                    });

                    this.selectedItems = [];
                    this.loadDetails();
                } catch (error) {
                    console.error('批量审核失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '审核失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },
        handleZoom() {
            // 更新CSS变量
            document.documentElement.style.setProperty('--preview-width', `${this.zoomLevel}%`);
            // 保存到 localStorage
            localStorage.setItem('auditPreviewZoom', this.zoomLevel);
        },
        async loadStats() {
            try {
                const response = await fetch('/api/admin/details/stats');
                const data = await response.json();
                if (data.code === 200) {
                    this.stats = data.data;
                }
            } catch (error) {
                console.error('加载统计数据失败:', error);
            }
        },
        handleScroll() {
            // 获取滚动容器
            const container = document.querySelector('.table-responsive');
            if (!container) return;

            // 检查是否接近底部
            const scrollBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
            if (scrollBottom < 100 && !this.loading && this.hasMore) {
                this.currentPage++;
                this.loadDetails();
            }
        }
    },
    mounted() {
        this.loadTemplates();
        this.loadDetails();
        this.loadStats();

        // 从 localStorage 恢复缩放级别
        const savedZoom = localStorage.getItem('auditPreviewZoom');
        if (savedZoom) {
            this.zoomLevel = parseInt(savedZoom);
            this.handleZoom();
        }

        // 添加滚动监听
        const container = document.querySelector('.table-responsive');
        if (container) {
            container.addEventListener('scroll', this.handleScroll);
        }
    },
    beforeDestroy() {
        // 移除滚动监听
        const container = document.querySelector('.table-responsive');
        if (container) {
            container.removeEventListener('scroll', this.handleScroll);
        }
    },
    watch: {
        selectedTemplate() {
            this.currentPage = 1;
            this.hasMore = true;
            this.loadDetails();
            this.loadStats();
        }
    }
}).mount('#auditApp'); 